<?php
declare (strict_types=1);

namespace app\common\model;

use app\common\facade\Target;
use app\common\facade\WeChat;
use app\common\facade\WeChatMini;
use app\common\model\Statistics as StatisticsModel;
use app\common\tool\pay\Pay;
use app\common\tool\Target\Driver\Account;
use think\facade\Cache;
use think\facade\Event;
use WeChat\Contracts\Tools;

class ActivityOrder extends Base
{
    protected $name = 'activity_order';

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function express()
    {
        return $this->hasOne(Express::class, 'id', 'express_id');
    }

    public function getPayWayAttr($value)
    {
        return get_pay_way($value);
    }

    public function getStatusAttr($value)
    {
        return getOrderStatus($value);
    }

    public function getRefundTypeAttr($value)
    {
        switch ($value) {
            case 1:
                return '退回余额';
            case 2:
                return '退回微信';
            default:
                return '其他';
        }
    }

    public function getIsRefundAttr($value)
    {
        switch ($value) {
            case 0:
                return '正常';
            case 1:
                return '退款中';
            case 2:
                return '已通过';
            case 3:
                return '已驳回';
            default:
                return '其他';
        }
    }

    public function getPostTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '未发货';
    }

    public function getRefundTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '未申请退款';
    }

    public function getPRefundTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i:s', $value) : '未处理退款';
    }

    public static function getTakeOverTableList($that, $param, $filed = '*', $count = 0)
    {
        try {
            foreach ($that as &$v) {
                $products = OrderProduct::where('order_id', $v->id)->field('pid,product_title,num')->select()->toArray();
                foreach ($products as $item) {
                    $v->productss .= $item['product_title'] . ' ' . "\n";
                }
                $v->pay_time = $v->pay_time ? date('Y-m-d H:i:s', intval($v->pay_time)) : '待付款';
                $v->statusRaw = $v->getData('status');
            }
//            dump($that);die;
            return ['code' => 0, 'data' => $that, 'count' => $count];
        } catch (\Exception $e) {
            return [];
        }
    }


    public static function drawback($param, $admin)
    {
        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }
            $info->is_refund = $param['is_refund'];

            if ($param['is_refund'] == 2) {
                $info->status = 4;
                if ($info->pay_way == '余额') {
                    $info->refund_type = 1;
                    Target::Account()
                        ->basics($info->uid, 'balance', $info->real_amount, '退款', '+')
                        ->createNormal($info->uid);
                } else {
                    $info->refund_type = 2;
                }
                $msg = '通过了退款信息，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $m = '已通过';
            } else {
                $info->status = 2;
                $msg = '驳回了退款信息，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $m = '已驳回';
            }
            $info->refund_time = time();
            $info->save();
            Logs::adds($msg, $admin->id, $admin->admin_name);

            return ['code' => 1, 'msg' => $m];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $param -- 提交的参数
     * @param $admin -- 后台当前登录管理员
     * @return array
     * 原点 2022年1月8日16:45:49 后台发货订单
     */
    public static function deliver($param, $admin)
    {

        try {
            $info = parent::find($param['id']);
            if ($info->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到相关订单'];
            }
            $status = $info->status;
            $info->express_id = $param['express_id'];
            $info->express_code = $param['express_code'];
            $info->receiver = $param['receiver'];
            $info->receiver_tel = $param['receiver_tel'];
            $info->province = $param['province'];
            $info->city = $param['city'];
            $info->district = $param['district'];
            $info->town = $param['town'];
            $info->address_details = $param['address_details'];
            $info->post_remark = $param['post_remark'];
            $info->post_time = time();

            $info->status = 3;
            $res = $info->save();
//
            $route = 'callback/send.log';
            $order_product = OrderProduct::where('order_id',$info->id)->find();
            $user = User::find($info->uid);
            $express = Express::find($param['express_id']);

            $data = [
                'order_key'=>[
                    'order_number_type'=>1,
                    'mchid'=>'1649250656',
                    'out_trade_no'=>$info->sn,
                ],
                'logistics_type'=>1,
                'delivery_mode'=>1,
                'shipping_list'=>[
                    [
                        'tracking_no'=> $param['express_code'],
                        'express_company'=> $express->code,
                        'item_desc'=>$order_product->product_title,
                        'contact'=>[
                            'consignor_contact'=>'+86-'.substr($param['receiver_tel'],0,3).'****'.substr($param['receiver_tel'],-4,4)
                        ],
                    ]
                ],
                'upload_time'=>date(DATE_RFC3339,time()),
                'payer'=>['openid'=>$user->openid]
            ];
//dump($data);die;
            $result = WeChatMini::deliverAdd($data);
            Logs::write($route, json_encode($result));

            if ($res !== true) {
                return ['code' => -1, 'msg' => '发货失败'];
            }
            if ($status < 3) {
                $msg = '订单发货，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $m = '已发货';
            } else {
                $msg = '修改了发货信息，订单号【' . $info->sn . '】下单会员【' . $info->user->code . '】';
                $m = '已修改';
            }

            Logs::adds($msg, $admin->id, $admin->admin_name);
            return ['code' => 1, 'msg' => $m];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid -- 会员ID
     * @return array
     * 原点 2022年1月8日16:45:24 获得会员临时暂存的订单
     */
    public static function getTemporary($uid): array
    {
        try {
            $temporary = Cache::get('activityOrder_' . $uid);
//            dump($temporary);die;
            if (empty($temporary)) {
                return ['code' => -1, 'msg' => '加载失败', 'data' => ''];
            }
            $infos = json_decode($temporary, true);

            $activity = Activity::where(['is_del' => 0, 'status' => 1, 'id' => $infos['aid']])
                ->field('id,title,images,price')->find();
            if (empty($activity))  return ['code' => -1, 'msg' => '活动不存在'];
            $total = $activity->price;

            $data = [
                'activity' => $activity,
                'total' => $total,
                'name' => $infos['name'],
                'phone' => $infos['phone'],
                'address' => $infos['address'],
            ];
            return ['code' => 1, 'msg' => '获取成功', 'data' => $data];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $address_id -- 选择地址ID
     * @param $user -- 会员信息
     * @return array
     * 原点 2022年1月8日16:44:54 提交产生待支付订单
     */
    public static function submit($user, $param): array
    {
        $temporary = self::getTemporary($user->id);
        $temporary = $temporary['data'];
        if (empty($temporary) || empty($temporary['activity'])) {
            return ['code' => -1, 'msg' => '加载失败，请稍后再试'];
        }
        if (!$temporary['total'] || $temporary['total'] <= 0) {
            return ['code' => -1, 'msg' => '订单价格错误！'];
        }
        parent::startTrans();
        try {
            $new = parent::create([
                'sn' => 'HD'.date('Ymd') . $user->id . time(),
                'uid' => $user->id,
                'a_id' => $temporary['activity']['id'],
                'total_amount' => $temporary['total'],
                'real_amount' => $temporary['total'],
                'receiver' => $temporary['name'],
                'receiver_tel' => $temporary['phone'],
                'address_details' => $temporary['address'],
            ]);

            parent::commit();
            Cache::set('activityOrder_' . $user->id, null);
            Cache::set('nowActivityOrderId_' . $user->id, $new->id);
            return ['code' => 1, 'msg' => '已生成订单','id'=> $new->id];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * @param $uid -- 会员ID
     * @return array
     * 原点 2022年1月8日16:44:08 获取当前会员待支付的订单
     * 每个会员同时只能下一个单，如有多个会替换掉！
     */
    public static function getNowOrder($uid): array
    {
        $now_id = Cache::get('nowActivityOrderId_' . $uid);
        if (!$now_id) {
            return ['code' => -1, 'msg' => '加载失败', 'data' => ''];
        }
        $info = parent::where(['id' => $now_id, 'uid' => $uid, 'status' => 1, 'pay_state' => 0])->find();
        if (empty($info)) {
            return ['code' => -1, 'msg' => '订单不存在或已支付', 'data' => ''];
        }
        return ['code' => 1, 'result' => $info, 'data' => ''];
    }

    /**
     * @param $param -- 支付提交参数
     * @param $user -- 会员信息
     * @return array
     * 原点 2022年1月8日16:42:30 确认支付
     */
    public static function confirmPayment($param, $user): array
    {
        if (isset($param['a_id']) && $param['a_id']) {
            $order = ActivityOrder::find($param['a_id']);
        } else {
            $info = self::getNowOrder($user->id);
            if ($info['code'] != 1) return $info;
            $order = $info['result'];
        }
        $account = $param['pay_way'];
        switch ($account) {
            case "integral":
            case "balance":
                if ($user->assets->$account < $order->real_amount) {
                    return ['code' => -1, 'msg' => '账户余额不足', 'data' => ''];
                }
                return self::operation($order, $user, $account);
            case "wechat":
//                return ['code' => -1, 'msg' => '暂未开放'];
                $notifyUrl = 'https://' . $_SERVER['HTTP_HOST'] . '/api/callback/wechatCallback';
                //设置参数
                $options = \app\common\facade\Pay::setDriver('WeChat')
                    ->basic('购买商品', $order->sn, $order->real_amount, $notifyUrl)
                    ->setOpenId($user->openid)
                    ->create('JSAPI');
                return ['code' => 1, 'msg' => '微信支付', 'data' => $options];

            default:
                return ['code' => -1, 'msg' => '请选择支付方式'];
        }

    }

    /**
     * @param $order -- 订单信息
     * @param $user -- 会员信息
     * @param $pay_way -- 支付方式
     * @return array
     * 原点 2022年1月8日16:42:02 支付完成后续操作
     */
    public static function operation($order, $user, $pay_way)
    {
        parent::startTrans();
        try {
            //其他后续操作，按需执行
            //更改状态
            $order->pay_state = 2;
            $order->pay_way = $pay_way;
            $order->pay_time = time();
            $order->status = 2;
            $order->save();

            //扣钱
            if (!in_array($pay_way, ['wechat', 'alipay'])) {
                Target::Account()
                    ->basics($user->id, $pay_way, $order->real_amount, '购买产品', '-')
                    ->lock(false)
                    ->createNormal($user->id);
            }

            if($user->is_receive == 0)
            {
                User::update(['is_receive' => 1], ['id' => $user->id]);
            }

            //根据分区不同，处理不同逻辑
//            switch ($order->order_type) {
//                case 1:
//                    if($user->is_active == 1)
//                    {
//                        Relation::update(['status' => 1], ['new_uid' => $user->id]);
//                        User::update(['is_active' => 2,'level_id'=>$order->level_id,'active_time'=>time()], ['id' => $user->id]);
//                    }
//                    User::where('id', $user->id)->inc('my_total', floatval($order->real_amount))->update();//个人业绩
//                    Relation::renewTeamTotal($order->real_amount,$user->id);//团队业绩
//
//                    break;
//                case 2:
//                    break;
//                default:
//                    break;
//            }
//            StatisticsModel::_update($order->real_amount, 'income');
//            //直推收益
//            if($user->parent_id)
//            {
//                $direct_push = 'direct_push_'.$order->order_type;
//                $direct_push = cache('system')[$direct_push];
////                $amount = bcmul((string)$order->real_amount, (string)$direct_push, 2);//
//                $amount = round($order->real_amount*$direct_push, 2);
//                Target::Account()
//                    ->basics($user->parent_id, 'integral', $amount, '直推收益', '+')
//                    ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
//                    ->createBonus($user->id, '1');
//                User::where('id', $user->parent_id)->inc('my_income', floatval($amount))->update();//累计收入
//                //分享收益
//                Relation::share_reward($user->parent_id,$amount,$order->order_type);
//                StatisticsModel::_update($amount, 'expend');
//
//            }
//
//
//            //管理收益
//            Relation::manage_income($user->id,$order->real_amount);
//
//            //升级
//            $res = Relation::upgrade($user->id);
//            if ($res['code'] != 1) {
//                parent::rollback();
//                return ['code' => -1, 'msg' => '加载失败：upgrade'];
//            }

//            Event::trigger('Statistics', ['key' => 'income', 'value' => $order->real_amount]);
//            Event::trigger('Operation', $order->id);
            StatisticsModel::_update(1, 'order');
            parent::commit();
            Cache::set('nowOrderId_' . $user->id, null);
            return ['code' => 1, 'msg' => '支付成功', 'data' => ''];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }

    }



    //分红
    public static function bonus()
    {
      $amount = Order::where(['pay_state'=>2,'is_bonus'=>0])->sum('real_amount');
      if($amount)
      {
          $bonus = cache('system')['bonus'];
          $amount = bcmul((string)$amount, (string)$bonus, 2);//
          $users = User::where(['level_id'=>3,'is_del'=>0])->column('id');
          $sum = count($users);
          $num = 0;
          if($sum)
          {
//              $amount = bcdiv((string)$amount, (string)$bonus, 2);//
              $amount = round($amount/$bonus, 2);
              foreach ($users as $k=>$v) {
                  Target::Account()
                      ->basics($v, 'integral', $amount, '分红', '+')
                      ->lock(false)//写入流水是否上锁，默认false,开启后会大幅降低性能，开启后必须配合事务使用
                      ->createBonus($v, '4');
                  User::where('id', $v)->inc('my_income', floatval($amount))->update();//累计收入
                  $num+=$amount;
              }
              StatisticsModel::_update($num, 'expend');
          }
      }
        return ['code'=>1,'msg'=>'处理成功！'];
    }

    //推送消息
//    public static function Push_news($order,$user)
//    {
////        $OrderProduct = OrderProduct::where('order_id',$order->id)->find();
//        //微信公众号获取消息模板列表draw_cost
//        WeChat::getAllPrivateTemplate();
//        //发送模板消息已下单消息模板数据
//        $message_pusher = explode(',', cache('system')['message_pusher']);
//        foreach ($message_pusher as $k=>$v){
//            $wedata = [
//                'touser' => $v,
//                'template_id' => 'zX9tYHHsIHCVUhM7AHnFUMJgnuOa3VSsje5DwE6cPiQ',
//                'url'  => '',
//                'data' => [
//                    'first' => [
//                        'value' => '收到客户下单通知',
//                        'color' => '#173177'
//                    ],
//                    'keyword1' => [
//                        'value' => $order->sn,
//                        'color' => '#173177'
//                    ],
//                    'keyword2' => [
//                        'value' => "商城订单",
//                        'color' => '#173177'
//                    ],
//                    'keyword3' => [
//                        'value' => $order->real_amount,
//                        'color' => '#173177'
//                    ],
//                    'keyword4' => [
//                        'value' => $order->create_time,
//                        'color' => '#173177'
//                    ],
//                    'keyword5' => [
//                        'value' =>  $user->nickname,$user->mobile,
//                        'color' => '#173177'
//                    ],
//                    'remark' => [
//                        'value' => '',
//                        'color' => '#173177'
//                    ]
//                ]
//            ];
//            //发送模板消息
//            WeChat::wechatTemplateSend($wedata);
//        }
//
//
//    }


    public static function Push_news($order,$user)
    {
        try {
            $route = 'callback/Push_news.log';
            Logs::write($route,'发送模板');
            WeChat::withConfig(config('pay')['wechat_1'])->getAllPrivateTemplate();
//            $message_pusher = explode(',', cache('system')['message_pusher']);
//            foreach ($message_pusher as $k=>$v)
//            {
                $wedata = [
                    'touser' =>  cache('system')['message_pusher'],
                    'template_id' => 'zX9tYHHsIHCVUhM7AHnFUMJgnuOa3VSsje5DwE6cPiQ',
                    'url'  => '',
                    'data' => [
                        'first' => [
                            'value' => '收到客户下单通知',
                            'color' => '#173177'
                        ],
                        'keyword1' => [
                            'value' => $order->sn,
                            'color' => '#173177'
                        ],
                        'keyword2' => [
                            'value' => "商城订单",
                            'color' => '#173177'
                        ],
                        'keyword3' => [
                            'value' => $order->real_amount,
                            'color' => '#173177'
                        ],
                        'keyword4' => [
                            'value' => $order->create_time,
                            'color' => '#173177'
                        ],
                        'keyword5' => [
                            'value' =>  $user->nickname,$user->mobile,
                            'color' => '#173177'
                        ],
                        'remark' => [
                            'value' => '',
                            'color' => '#173177'
                        ]
                    ]
                ];
                $msg = WeChat::withConfig(config('pay')['wechat_1'])->wechatTemplateSend($wedata);

                Logs::write($route,$msg);
//             }
        } catch (\Exception $e) {
            parent::rollback();
            Logs::write($route,$e->getMessage());
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        //发送模板消息

    }




    /**
     * @param $param
     * @param $user
     * @return array
     * 原点 2022年1月8日16:43:09 订单相关操作
     */
    public static function edit($param, $user): array
    {
        try {
            $info = parent::where(['id' => $param['id'], 'uid' => $user->id, 'is_del' => 0])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '订单不存在'];
            }
            switch ($param['type']) {
                case 'clear': //取消订单
                    if ($info->getData('status') != 1 || $info->pay_state) {
                        return ['code' => -1, 'msg' => '订单已支付，无法取消'];
                    }
                    $info->is_del = 1;
                    $info->status = 5;
                    $info->cancel_time = time();
                    $info->save();
                    return ['code' => 1, 'msg' => '订单已取消'];
                case 'payment': //支付订单
                    if ($info->getData('status') != 1) {
                        return ['code' => -1, 'msg' => '订单已支付'];
                    }
                    Cache::set('nowOrderId_' . $user->id, $info->id);
                    return ['code' => 4, 'msg' => '已生成订单', 'url' => url('order/payment')->build()];

                case "remind": //提醒发货
                    if ($info->getData('status') != 2) {
                        return ['code' => -1, 'msg' => '订单未支付或已发货'];
                    }
                    if ($info->is_remind) {
                        return ['code' => -1, 'msg' => '您已提醒发货了！'];
                    }
                    $info->is_remind = 1;
                    $info->remind_time = time();
                    $info->save();
                    return ['code' => 1, 'msg' => '已提醒发货'];
                case "receipt": //确认收货
                    if ($info->getData('status') != 3) {
                        return ['code' => -1, 'msg' => '订单异常'];
                    }
                    $info->status = 4;
                    $info->receipt_time = time();
                    $info->save();
                    return ['code' => 1, 'msg' => '已确认收货'];
                default:
                    return ['code' => -1, 'msg' => '加载失败'];

            }
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

}
